﻿namespace ConsoleApplication1
{
	using System;
	using System.Linq;
	using System.Web.Services.Protocols;
	using System.Xml.Linq;
	using Noaa.Noaa;

	public class Program
	{
		private static void Main()
		{
			IWeatherClient client = new WeatherClient();

			//Get lat/lon for zipcode
			while (true)
			{
				Console.WriteLine("Enter zip code: ");
				var zipCode = Console.ReadLine();
				XElement latitudeLongitude = GetLatitudeLongitude(client, zipCode);
				XDocument document;
				string data;
				if (latitudeLongitude == null || string.IsNullOrEmpty(latitudeLongitude.Value))
				{
					Console.WriteLine("Cannot get latitude / longitude");
					continue;
				}

				var location = latitudeLongitude.Value.Split(',');
				decimal latitude;
				if (location.Count() != 2 || !Decimal.TryParse(location[0], out latitude))
				{
					Console.WriteLine("Invalid latitude");
					continue;
				}
				decimal longitude;
				if (!Decimal.TryParse(location[1], out longitude))
				{
					Console.WriteLine("Invalid longitude");
					continue;
				}
				Console.WriteLine("ZipCode: {0}, Latitude {1} Longitude {2}", zipCode, latitude, longitude);

				//Get max temperature for zip code
				int days = 10;

				weatherParametersType weatherParameters = new weatherParametersType();
				weatherParameters.maxt = true;
				weatherParameters.mint = true;
				data = client.NDFDgenByDay(latitude, longitude, DateTime.Now, days.ToString(), formatType.Item24hourly);
				document = XDocument.Parse(data);
				var parameters = document.Descendants("parameters").FirstOrDefault();
				if (parameters == null)
				{
					Console.WriteLine("Cannot get weather data");
					continue;
				}
				var maxTemperatures =
					parameters.Descendants("temperature").FirstOrDefault(
						t => t.Attribute("type") != null && t.Attribute("type").Value == "maximum").Descendants("value").ToList();
				var minTemperatures =
					parameters.Descendants("temperature").FirstOrDefault(
						t => t.Attribute("type") != null && t.Attribute("type").Value == "minimum").Descendants("value").ToList();

				for (int i = 0; i < maxTemperatures.Count; i++)
				{
					var date = DateTime.Now.AddDays(i);

					Console.WriteLine("{0:d} min: {1}, max {2}",
									  date,
									  minTemperatures[i].Value,
									  maxTemperatures[i].Value);
				}
			}
		}

		public static XElement GetLatitudeLongitude(IWeatherClient client, string zipCode)
		{
			string data;
			try
			{
				data = client.LatLonListZipCode(zipCode);
			}
			catch (SoapException exception)
			{
				return null;
			}
			XDocument document = XDocument.Parse(data);
			return document.Descendants("latLonList").FirstOrDefault();
		}
	}
}